import SendMsg from "@/api/SendMsg";
import {message} from "ant-design-vue";
import router from "@/router";
import store from "../../index";
import request from "../../../util/request";
import moment from "moment";

const VisualInspectionReport = {
    namespaced: true,
    state: {
        // table数据
        dataSource: [],
        dataSource2: [],
        dataSource3: [],
        dataSourceDetail: [],
        //弹窗
        VisualInspectionReportDetailVisible:false,

        // 查询条件
        queryForm: {
            lotId: '',
        },
        queryLotInfoForm: {
            technology: '',
            productName: '',
            customerCode: '',
            quantity: '',
            evtUsr: '',
            evtTimestamp: '',
        },
        lotList: [],
        loadTable: false,
        // 编辑表单数据
        capForm: {
            comment: '',
            evtCate: '',
        },
        // table选中行
        selectRow: {},
        deptType: '',
    },
    mutations: {
        //查询table1
        queryTableList(state) {
            if(!state.queryForm.lotId){
                message.warn("Please Select a lotId")
                return
            }
            VisualInspectionReport.mutations.queryEngTableList(state)
            VisualInspectionReport.mutations.querySelectList(state)
            VisualInspectionReport.mutations.queryLotComment(state)
            let codeInTrx = {
                trxId: "retLot",
                actionFlg: "QMA",
                lotId: state.queryForm.lotId,
            };
            state.dataSource = []
            state.dataSource2 = []
            state.loadTable = true
            SendMsg.sendPostTrx(codeInTrx).then((res) => {
                let outTrx = res.data;
                if ('0000000' === outTrx.rtnCode) {
                    state.dataSource = outTrx.oaryD.map((item, index) => {
                        item.key = (index + 1);
                        return item;
                    });
                }
            }).finally(() => {
                state.loadTable = false
            });
        },
        //查询table2
        queryEngTableList(state) {
            let codeInTrx = {
                trxId: "retLot",
                actionFlg: "QENG",
                lotId: state.queryForm.lotId,
            };
            state.dataSource2 = []
            state.loadTable = true
            SendMsg.sendPostTrx(codeInTrx).then((res) => {
                let outTrx = res.data;
                if ('0000000' === outTrx.rtnCode) {
                    state.dataSource2 = outTrx.oaryE.map((item, index) => {
                        item.key = (index + 1);
                        return item;
                    });
                }
            }).finally(() => {
                state.loadTable = false
            });
        },
        //查询table MA detail info
        queryTableDetailList(state) {
            let codeInTrx = {
                trxId: "retLot",
                actionFlg: "QVIDETAIL",
                lotId: state.queryForm.lotId,
                waferId: state.selectRow.waferId,
                site: state.selectRow.site,
                deptType: "MA",
            };
            state.deptType = "MA"
            state.dataSourceDetail = []
            state.loadTable = true
            SendMsg.sendPostTrx(codeInTrx).then((res) => {
                let outTrx = res.data;
                if ('0000000' === outTrx.rtnCode) {
                    state.dataSourceDetail = outTrx.oaryF.map((item, index) => {
                        item.key = (index + 1);
                        return item;
                    });
                }
            }).finally(() => {
                state.loadTable = false
            });
        },
        //查询table Eng detail info
        queryEngTableDetailList(state) {
            let codeInTrx = {
                trxId: "retLot",
                actionFlg: "QVIDETAIL",
                lotId: state.queryForm.lotId,
                waferId: state.selectRow.waferId,
                site: state.selectRow.site,
                deptType: "ENG",
            };
            state.deptType = "ENG"
            state.dataSourceDetail = []
            state.loadTable = true
            SendMsg.sendPostTrx(codeInTrx).then((res) => {
                let outTrx = res.data;
                if ('0000000' === outTrx.rtnCode) {
                    state.dataSourceDetail = outTrx.oaryF.map((item, index) => {
                        item.key = (index + 1);
                        return item;
                    });
                }
            }).finally(() => {
                state.loadTable = false
            });
        },
        // 查询lot下拉框数据
        queryLotList(state,data) {
            let intrx = {
                trxId: "retLot",
                actionFlg: "QL",
                flg: 'X',
                lotId: data,
            };
            SendMsg.sendPostTrx(intrx).then((res) => {
                let outTrx = res.data;
                if ('0000000' === outTrx.rtnCode) {
                    state.lotList = outTrx.oaryB
                }
            })
        },
        // 查询lot comment数据
        queryLotComment(state) {
            let intrx = {
                trxId: "retLot",
                actionFlg: "QCOMMENT",
                lotId: state.queryForm.lotId,
            };
            SendMsg.sendPostTrx(intrx).then((res) => {
                let outTrx = res.data;
                if ('0000000' === outTrx.rtnCode) {
                    state.capForm.comment = outTrx.dnComment
                }
            })
        },
        queryRetWaferInfo(state,val) {
            let codeInTrx = {
                trxId: "normalLot",
                actionFlg: "QWAFER",
                lotId: val
            };
            state.dataSource3 = []
            state.loadTable = true
            SendMsg.sendPostTrx(codeInTrx).then((res) => {
                let outTrx = res.data;
                if ('0000000' === outTrx.rtnCode) {
                    state.dataSource3 = outTrx.normalLotOBList.map((item, index) => {
                        item.key = (index + 1);
                        return item;
                    });
                }
            }).finally(() => {
                state.loadTable = false
            });
        },
        // lot下拉框带出相关信息
        querySelectList(state) {
            let intrx = {
                trxId: "retLot",
                actionFlg: "QSELECTHIS",
                lotId: state.queryForm.lotId,
            };
            SendMsg.sendPostTrx(intrx).then((res) => {
                let outTrx = res.data;
                if ('0000000' === outTrx.rtnCode) {
                    if (outTrx.oaryC.length > 0) {
                        state.queryLotInfoForm = outTrx.oaryC[0];
                        if (state.queryLotInfoForm.technology === '' || state.queryLotInfoForm.technology === undefined){
                            state.queryLotInfoForm.technology  = 'NA'
                        }
                        if (state.queryLotInfoForm.productName === '' || state.queryLotInfoForm.productName === undefined){
                            state.queryLotInfoForm.productName  = 'NA'
                        }
                        if (state.queryLotInfoForm.customerCode === '' || state.queryLotInfoForm.customerCode === undefined){
                            state.queryLotInfoForm.customerCode  = 'NA'
                        }
                        if (state.queryLotInfoForm.quantity === '' || state.queryLotInfoForm.quantity === undefined){
                            state.queryLotInfoForm.quantity  = 'NA'
                        }
                        if (state.queryLotInfoForm.evtUsr === '' || state.queryLotInfoForm.evtUsr === undefined){
                            state.queryLotInfoForm.evtUsr  = 'NA'
                        }
                        if (state.queryLotInfoForm.evtTimestamp === '' || state.queryLotInfoForm.evtTimestamp === undefined){
                            state.queryLotInfoForm.evtTimestamp  = 'NA'
                        }
                    }
                }
            })
        },
        //Wafer Visual Inspection Record Form导出
        exportExcel(state) {
            if(!state.dataSource.length>0){
                message.warn("No Data!")
                return
            }

            //查厚片lot
            let srcLot = ''
            let intrx = {
                trxId: "retLot",
                actionFlg: "BGBMLOT",
                lotId: state.queryForm.lotId,
            };
            SendMsg.sendPostTrx(intrx).then((res) => {
                let outTrx = res.data;
                if ('0000000' === outTrx.rtnCode) {
                    srcLot = outTrx.lotId
                }
            })

            let inTrx = {
                trxId: "retLot",
                actionFlg: "E",
                lotId: state.queryForm.lotId,
            };
            let name = 'Visual Inspection Report';
            inTrx.fabIdFk = window.localStorage.getItem("fabIdMes");
            inTrx.evtUsr = window.localStorage.getItem("userIdMes");
            request({
                url:  `/EOQC/export/retLot/E`,
                method: "post",
                data: {
                    trxId: inTrx.trxId,
                    strInMsg: JSON.stringify(inTrx)
                },
                responseType: 'blob',
            }).then(({data, ...res}) => {
                if (res.headers['content-type'].indexOf("application/json") !== -1) {
                    let reader = new FileReader();
                    reader.onload = event => {
                        let content = reader.result;//内容就在这里
                        let result = JSON.parse(content)
                        if (result.rtnCode !== '000000') {
                            // that.setErrorCodeForm(result.rtnMsg);
                            // that.setErrorCodeVisible(true);
                            store.commit('ErrorCode/setErrorCodeVisible', true)
                            store.commit('ErrorCode/setErrorCodeForm', result)
                        }
                    };
                    reader.readAsText(data);
                } else {
                    const blob = new Blob([data]);
                    // const fileName = new Date().getTime()+'.xls';
                    //YYYY﹣MM﹣DD  HH︰mm︰ss`

                    let fileName = ''
                    if (!srcLot){
                        fileName = name + ' ' + state.queryForm.lotId + '.xls';
                    }else{
                        fileName = name + ' ' + srcLot + '-' + state.queryForm.lotId + '.xls';
                    }

                    const linkNode = document.createElement('a');

                    linkNode.download = fileName; //a标签的download属性规定下载文件的名称s
                    linkNode.style.display = 'none';
                    linkNode.href = URL.createObjectURL(blob); //生成一个Blob URL
                    document.body.appendChild(linkNode);
                    linkNode.click();  //模拟在按钮上的一次鼠标单击

                    URL.revokeObjectURL(linkNode.href); // 释放URL 对象
                    document.body.removeChild(linkNode);
                }

            })
        },
        //Wafer Visual Inspection Record Form Detail导出
        exportDetailExcel(state) {
            if(!state.dataSourceDetail.length>0){
                message.warn("No Data!")
                return
            }
            let inTrx = {
                trxId: "retLot",
                actionFlg: "QVIDETAIL",
                lotId: state.queryForm.lotId,
                waferId: state.selectRow.waferId,
                site: state.selectRow.site,
                evtCate: state.capForm.evtCate,
                deptType: state.deptType
            };
            let name = 'Visual Inspection Report Detail';
            inTrx.fabIdFk = window.localStorage.getItem("fabIdMes");
            inTrx.evtUsr = window.localStorage.getItem("userIdMes");
            request({
                url:  `/EOQC/exportDetail/retLot/QVIDETAIL`,
                method: "post",
                data: {
                    trxId: inTrx.trxId,
                    strInMsg: JSON.stringify(inTrx)
                },
                responseType: 'blob',
            }).then(({data, ...res}) => {
                if (res.headers['content-type'].indexOf("application/json") !== -1) {
                    let reader = new FileReader();
                    reader.onload = event => {
                        let content = reader.result;//内容就在这里
                        let result = JSON.parse(content)
                        if (result.rtnCode !== '000000') {
                            // that.setErrorCodeForm(result.rtnMsg);
                            // that.setErrorCodeVisible(true);
                            store.commit('ErrorCode/setErrorCodeVisible', true)
                            store.commit('ErrorCode/setErrorCodeForm', result)
                        }
                    };
                    reader.readAsText(data);
                } else {
                    const blob = new Blob([data]);
                    // const fileName = new Date().getTime()+'.xls';
                    //YYYY﹣MM﹣DD  HH︰mm︰ss`
                    const fileName = name + moment().format(` YYYY-MM-DD`) + '.xls';
                    const linkNode = document.createElement('a');

                    linkNode.download = fileName; //a标签的download属性规定下载文件的名称s
                    linkNode.style.display = 'none';
                    linkNode.href = URL.createObjectURL(blob); //生成一个Blob URL
                    document.body.appendChild(linkNode);
                    linkNode.click();  //模拟在按钮上的一次鼠标单击

                    URL.revokeObjectURL(linkNode.href); // 释放URL 对象
                    document.body.removeChild(linkNode);
                }

            })
        },
        // 清空弹窗数据
        cleanData(state) {
            state.queryForm = {
                lotId: '',
            }
            state.queryLotInfoForm = {
                technology: '',
                productName: '',
                customerCode: '',
                quantity: '',
                evtUsr: '',
                evtTimestamp: '',
            }
            state.dataSource = []
            state.dataSource2 = []
            state.dataSource3 = []
        },

        clickCell(state,record){
            state.selectRow = {
                lotId: record.lotId,
                waferId: record.waferId,
                site: record.site,
            }
            state.VisualInspectionReportDetailVisible = true
            state.capForm.evtCate = 'WJGE'
            VisualInspectionReport.mutations.queryTableDetailList(state);
        },
        clickCellEng(state,record){
            state.selectRow = {
                lotId: record.lotId,
                waferId: record.waferId,
                site: record.site,
            }
            state.VisualInspectionReportDetailVisible = true
            state.capForm.evtCate = 'EJGE'
            VisualInspectionReport.mutations.queryEngTableDetailList(state);
        },
        VisualInspectionReportDetailOk(state){
            state.VisualInspectionReportDetailVisible = false
            state.VisualInspectionReportVisible = true
        },
    },
    getters: {},
    action: {}
}
export default VisualInspectionReport;
